package com.excel.controller;

import com.excel.entity.Excel;
import com.excel.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

@RestController
@RequestMapping("/api/excel")
@CrossOrigin
public class ExcelController {
    private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);
    //添加日志信息


    @Autowired
    private ExcelService service;

    @GetMapping
    public ResponseEntity<List<Excel>> getAll() {
        logger.info("匹配所有excel记录");
        return ResponseEntity.ok(service.findAll());
    }

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @PostMapping
    public Excel create(@RequestBody Excel excel) {
        return service.save(excel);
    }

//
    @PutMapping("/{id}")
    public ResponseEntity<Excel> update(@PathVariable Integer id, @RequestBody Excel excel) {
        return service.findById(id)
                .map(record -> {
                    excel.setId(id); // 设置 ID
                    return ResponseEntity.ok(service.save(excel));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        if (service.findById(id).isPresent()) {
            service.deleteById(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/search")
    public List<Excel> search(@RequestParam String keyword) {
        return service.searchByProjectName(keyword);
    }

}
